import { ActionTree, createStore, GetterTree, MutationTree } from "vuex";
import { ResultVO } from "@/mock";
import * as vxt from "./VuexTypes";
import axios from "@/axios";
import {Appointment, Booking, Course, Laboratory, User} from "@/datasource/Type"
import router from "@/router";
import { Menu } from "@/role/Menu";
import { ElMessage, ElMessageBox } from "element-plus";

export interface State{
  isLogin?: boolean;
  exception?: string;
  role?:string;
  menuList?:Menu[];
  user?:User;
  loading?:boolean;
  teacherList?:User[];
  teacher?:User
  laboratoryList:Laboratory[];
  courseList:Course[]
  bookingList:Booking[]
  appointmentList:Appointment[]
}

const myState:State={
  isLogin:false,
  exception: "",
  role:"",
  menuList: [],
  user:{},
  loading:false,
  teacherList:[],
  laboratoryList:[],
  teacher:{},
  courseList:[],
  bookingList:[],
  appointmentList:[]
}

const myMutations: MutationTree<State> ={
  [vxt.UPDATE_EXCEPTION]: (state, data: string) => (state.exception = data),
  [vxt.SET_ROLE]: (state, data: string) => (state.role = data),
  [vxt.SET_MENULIST]:(state, data: Menu[]) => (state.menuList = data),
  [vxt.SET_USER]:(state, data: User) => (state.user = data),
  [vxt.LIST_TEACHERS]:(state, data:User[]) => {
    state.teacherList=data
    state.teacherList.forEach(t=>{
      t.createTime=t.createTime?.substr(0,10)+" "+t.createTime?.substr(11,5)
      t.updateTime=t.updateTime?.substr(0,10)+" "+t.updateTime?.substr(11,5)
    })
  },
  [vxt.LOADING]:(state, data) => {
    state.loading=data
  },
  [vxt.GET_TEACHER]:(state, data:User) => {
    state.teacher=data
  },
  [vxt.LIST_LABORATORY]:(state, data) => {
    state.laboratoryList=data
    state.laboratoryList.forEach(l=>{
      l.createTime=l.createTime?.substr(0,10)+" "+l.createTime?.substr(11,5)
      l.updateTime=l.updateTime?.substr(0,10)+" "+l.updateTime?.substr(11,5)
    })
  },
  [vxt.LIST_COURSE]:(state, data) => {
    state.courseList=data
    state.courseList.forEach(c=>{
      c.createTime=c.createTime?.substr(0,10)+" "+c.createTime?.substr(11,5)
      c.updateTime=c.updateTime?.substr(0,10)+" "+c.updateTime?.substr(11,5)
    })
  },
  [vxt.LIST_BOOKING]:(state, data:Booking[]) => {
    state.bookingList=data
  },
  [vxt.LIST_APPOINTMENT]:(state, data:Appointment[]) => {
    state.appointmentList=data
  },
}

const myActions: ActionTree<State, State> ={
  [vxt.LOGIN]:async ({ commit }, user)=>{
    try {
      const param = new URLSearchParams()
      param.append('userName', user.userName)
      param.append('password', user.password)
      const resp = await axios.post<ResultVO>("/api/login", param);
      //const resp = await axios.post<ResultVO>("/login", user);
      console.log("响应体是",resp);
      console.log(resp.headers.token);
      sessionStorage.setItem("token", resp.headers.token);
      const resultVO:ResultVO=resp.data
      console.log(resultVO.data.role);
      sessionStorage.setItem("role", resultVO.data.role);
      commit(vxt.SET_ROLE,resultVO.data.role);
      const { setUserRole } = await import("@/role/UserRole");
      const menuList = setUserRole(resultVO.data.role);
      commit(vxt.SET_MENULIST, menuList);
      console.log(resultVO.data.user);
      commit(vxt.SET_USER,resultVO.data.user)
      sessionStorage.setItem("user", JSON.stringify(resultVO.data.user));//vue用sessionStorage存对象时要用JSON.stringify，取对象时用JSON.parse
      router.push("/main");
    } catch (error) {
      // eslint默认禁止空执行体。加一段注释或关闭该检测
    }
    
  },
  [vxt.ADD_TEACHER]:async ({ commit }, teacher)=>{
    try {
      const param = new URLSearchParams()
      param.append('nickName', teacher.nickName)
      param.append('major', teacher.major)
      param.append('profession', teacher.profession)
      const resp = await axios.post<ResultVO>("/api/admin/teacher", param);
      const resultVO:ResultVO=resp.data
      console.log(resultVO.data);
      
      //console.log(resultVO.data);
      //commit(vxt.ADD_TEACHER,resultVO.data)
      ElMessageBox.alert(`用户名：${resultVO.data.teacher.userName} ,密码：${resultVO.data.teacher.password}`,"新增教师",{confirmButtonText: '确定', callback: () => {history.go(0)}})
    } catch (error) {
      // eslint默认禁止空执行体。加一段注释或关闭该检测
    }
    
  },
  [vxt.LIST_TEACHERS]:async ({ commit }, teacher)=>{
    try {
      console.log(teacher);
      commit(vxt.LOADING,true)
      const teacherJson=JSON.stringify(teacher)
      const resp = await axios.get<ResultVO>("/api/common/teachers",{params:{teacher:teacherJson}});
      const resultVO:ResultVO=resp.data
      console.log(resultVO);
      commit(vxt.LIST_TEACHERS,resultVO.data.teacherList)
      sessionStorage.setItem("teacherList", JSON.stringify(resultVO.data.teacherList))
      commit(vxt.LOADING,false)
    } catch (error) {
      // eslint默认禁止空执行体。加一段注释或关闭该检测
      commit(vxt.LOADING,false)
    }
    
  },
  [vxt.GET_TEACHER]:async ({ commit }, tid:string)=>{
    try {
      console.log("tid是",tid);
      const resp = await axios.get<ResultVO>(`/api/common/teacher/${tid}`);
      const resultVO:ResultVO=resp.data
      sessionStorage.setItem("teacher",JSON.stringify(resultVO.data.teacher))
    } catch (error) {
      // eslint默认禁止空执行体。加一段注释或关闭该检测
    }
    
  },
  [vxt.MODIFY_TEACHER]:async ({ commit }, teacher)=>{
    try {
      console.log(teacher);
      if(teacher.id){
        const tid=teacher.id
        const resp = await axios.put<ResultVO>(`/api/admin/teacher/${tid}`, {
          nickName:teacher.nickName,
          profession:teacher.profession,
          major:teacher.major
        });
        const resultVO:ResultVO=resp.data
        ElMessageBox.alert("更新成功","提示",{confirmButtonText: '确定', callback: () => {router.push("/admin/teachers")}})
      }
    } catch (error) {
      // eslint默认禁止空执行体。加一段注释或关闭该检测
    }
    
  },
  [vxt.DELETE_TEACHER]:async ({ commit }, tid:string)=>{
    try {
        const resp = await axios.delete<ResultVO>(`/api/admin/teacher/${tid}`);
        const resultVO:ResultVO=resp.data
        ElMessageBox.alert("删除成功","提示",{confirmButtonText: '确定', callback: () => {router.push("/admin/teachers")}})
      
    } catch (error) {
      // eslint默认禁止空执行体。加一段注释或关闭该检测
    }
    
  },
  [vxt.ADD_LABORATORY]:async ({ commit }, laboratory:Laboratory)=>{
    try {
        const param = new URLSearchParams()
        if(laboratory.name){
          param.append('name',laboratory.name )
        }
        if(laboratory.number){
          param.append('number', String(laboratory.number))
        }
        if(laboratory.description){
          param.append('description', laboratory.description)
        }
        const resp = await axios.post<ResultVO>("/api/admin/lab",param);
        const resultVO:ResultVO=resp.data
        ElMessageBox.alert("添加成功","提示",{confirmButtonText: '确定', callback: () => {history.go(0)}})
      
    } catch (error) {
      // eslint默认禁止空执行体。加一段注释或关闭该检测
    }
    
  },
  [vxt.LIST_LABORATORY]:async ({ commit })=>{
    try {
      commit(vxt.LOADING,true)
      const resp = await axios.get<ResultVO>("/api/common/labs");
      const resultVO:ResultVO=resp.data
      commit(vxt.LIST_LABORATORY,resultVO.data.laboratoryList)
      sessionStorage.setItem("laboratoryList", JSON.stringify(resultVO.data.laboratoryList))
      commit(vxt.LOADING,false)
    } catch (error) {
      // eslint默认禁止空执行体。加一段注释或关闭该检测
      commit(vxt.LOADING,false)
    }
    
  },
  [vxt.MODIFY_LABORATORY]:async ({ commit },laboratory:Laboratory)=>{
    try {
      if(laboratory.id){
        const lid=laboratory.id
        const resp = await axios.put<ResultVO>(`/api/admin/lab/${lid}`,laboratory);
        const resultVO:ResultVO=resp.data
        ElMessageBox.alert("更新成功","提示",{confirmButtonText: '确定', callback: () => {router.push("/admin/laboratories")}})
      }
        
    } catch (error) {
      // eslint默认禁止空执行体。加一段注释或关闭该检测
    }
    
  },
  [vxt.DELETE_LABORATORY]:async ({ commit }, lid:string)=>{
    try {
        const resp = await axios.delete<ResultVO>(`/api/admin/lab/${lid}`);
        const resultVO:ResultVO=resp.data
        ElMessageBox.alert("删除成功","提示",{confirmButtonText: '确定', callback: () => {router.push("/admin/laboratories")}})
      
    } catch (error) {
      // eslint默认禁止空执行体。加一段注释或关闭该检测
    }
    
  },
  [vxt.UPDATE_ADMIN_PASSWORD]:async ({ commit },data)=>{
    try {
        console.log(data.password);
        const resp = await axios.post<ResultVO>("/admin",data);
        const resultVO:ResultVO=resp.data
        ElMessageBox.alert("密码修改成功","提示",{confirmButtonText: '确定', callback: () => {history.go(0)}})
    } catch (error) {
      // eslint默认禁止空执行体。加一段注释或关闭该检测
    }
    
  },
  [vxt.ADMIN_UPDATE_TEACHER_PASSWORD]:async ({ commit },tid)=>{
    try {
      const resp = await axios.put<ResultVO>(`/api/admin/teacher/${tid}/password`);
        const resultVO:ResultVO=resp.data
        ElMessageBox.alert("密码修改成功","提示",{confirmButtonText: '确定'})
    } catch (error) {
      // eslint默认禁止空执行体。加一段注释或关闭该检测
    }
    
  },
  [vxt.UPDATE_TEACHER_PASSWORD]:async ({ commit },data)=>{
    try {
      const param = new URLSearchParams()
        if(data.password){
          param.append('pwd',data.password )
        }
      const resp = await axios.put<ResultVO>(`/api/teacher/${myState.user?.id}`,param);
        const resultVO:ResultVO=resp.data
        ElMessageBox.alert("密码修改成功","提示",{confirmButtonText: '确定', callback: () => {history.go(0)}})
    } catch (error) {
      // eslint默认禁止空执行体。加一段注释或关闭该检测
    }
    
  },
  [vxt.ADD_COURSE]:async ({ commit }, course:Course)=>{
    try {
        const param = new URLSearchParams()
        if(course.name){
          param.append('name',course.name )
        }
        if(course.number){
          param.append('number', String(course.number))
        }
        if(course.time){
          param.append('time', String(course.time))
        }
        const resp = await axios.post<ResultVO>(`/api/teacher/${myState.user?.id}/course`,param);
        const resultVO:ResultVO=resp.data
        ElMessageBox.alert("添加成功","提示",{confirmButtonText: '确定', callback: () => {history.go(0)}})
      
    } catch (error) {
      // eslint默认禁止空执行体。加一段注释或关闭该检测
    }
    
  },
  [vxt.LIST_COURSE]:async ({ commit })=>{
    try {
      commit(vxt.LOADING,true)
      const resp = await axios.get<ResultVO>(`/api/teacher/${myState.user?.id}/course`);
      const resultVO:ResultVO=resp.data
      commit(vxt.LIST_COURSE,resultVO.data.courseList)
      sessionStorage.setItem("courseList", JSON.stringify(resultVO.data.courseList))
      commit(vxt.LOADING,false)
    } catch (error) {
      // eslint默认禁止空执行体。加一段注释或关闭该检测
      commit(vxt.LOADING,false)
    }
    
  },
  [vxt.MODIFY_COURSE]:async ({ commit },course)=>{
    try {
      const cid=course.id
      const resp = await axios.put<ResultVO>(`/api/teacher/${myState.user?.id}/course/${cid}`,course);
        const resultVO:ResultVO=resp.data
        ElMessageBox.alert("更新成功","提示",{confirmButtonText: '确定', callback: () => {router.push("/teacher/courses")}})
    } catch (error) {
      // eslint默认禁止空执行体。加一段注释或关闭该检测
    }
    
  },
  [vxt.DELETE_COURSE]:async ({ commit }, cid:string)=>{
    try {
        const resp = await axios.delete<ResultVO>(`/api/teacher/${myState.user?.id}/course/${cid}`);
        const resultVO:ResultVO=resp.data
        ElMessageBox.alert("删除成功","提示",{confirmButtonText: '确定', callback: () => {router.push("/teacher/courses")}})
      
    } catch (error) {
      // eslint默认禁止空执行体。加一段注释或关闭该检测
    }
    
  },
  [vxt.SEARCHELAB]:async ({ commit }, cid:string)=>{
    try {
        const resp = await axios.get<ResultVO>(`/api/teacher/${myState.user?.id}/course/${cid}/appointment`);
        const resultVO:ResultVO=resp.data
        console.log(resultVO.data.laboratoryList);
        commit(vxt.LIST_LABORATORY,resultVO.data.laboratoryList)
    } catch (error) {
      // eslint默认禁止空执行体。加一段注释或关闭该检测
    }
    
  },
  [vxt.GET_LAB_APPOINTMENT]:async ({ commit }, lid:string)=>{
    try {
        const resp = await axios.get<ResultVO>(`/api/lab/${lid}/appointment`);
        const resultVO:ResultVO=resp.data
        //console.log(resultVO.data.appointmentList);
        commit(vxt.LIST_APPOINTMENT,resultVO.data.appointmentList)
    } catch (error) {
      // eslint默认禁止空执行体。加一段注释或关闭该检测
    }
    
  },
  [vxt.ADD_APPOINTMENT]:async ({ commit }, data)=>{
    try {
        const resp = await axios.post<ResultVO>(`/api/teacher/${myState.user?.id}/course/${data.cid}/lab/${data.lid}/appointment`,data.appointmentList);
        const resultVO:ResultVO=resp.data
        ElMessageBox.alert("添加成功","提示",{confirmButtonText: '确定', callback: () => {history.go(0)}})
    } catch (error) {
      // eslint默认禁止空执行体。加一段注释或关闭该检测
    }
    
  },
  [vxt.LIST_TEACHER_APPOINTMENT]:async ({ commit })=>{
    try {
        const resp = await axios.get<ResultVO>(`/api/teacher/${myState.user?.id}/appointment`);
        const resultVO:ResultVO=resp.data
        console.log(resultVO.data.appointmentList);
        
        commit(vxt.LIST_APPOINTMENT,resultVO.data.appointmentList)
    } catch (error) {
      // eslint默认禁止空执行体。加一段注释或关闭该检测
    }
    
  },
  [vxt.DELETE_APPOINTMENT]:async ({ commit }, ctId:string)=>{
    try {
        const resp = await axios.delete<ResultVO>(`/api/teacher/${myState.user?.id}/appointment/${ctId}`);
        const resultVO:ResultVO=resp.data
        ElMessageBox.alert("删除成功","提示",{confirmButtonText: '确定', callback: () => {history.go(0)}})
      
    } catch (error) {
      // eslint默认禁止空执行体。加一段注释或关闭该检测
    }
    
  },
}

const myGetters: GetterTree<State, State> ={

}
// 加载vuex时，判断登录/角色等信息，加载初始化数据
const token = sessionStorage.getItem("token");
if (token) {
  myState.isLogin = true;
}
const role=sessionStorage.getItem("role");
if(role){
  //eslint-disable-next-line @typescript-eslint/no-var-requires
  const user = require("@/role/UserRole.ts");
  myState.role = role;
  myState.menuList = user.setUserRole(role);
  console.log(myState.menuList);
  
}
const user=sessionStorage.getItem("user");
if(user){
   myState.user=JSON.parse(user)
}
export default createStore({
  state: myState,
  mutations: myMutations,
  actions: myActions,
  getters: myGetters,
  modules: {},
});
